package com.io.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.io.dto.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * The class/interface
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Slf4j
public class AspectUtils {
    /**
     * Spring MVC Controller层日志切片
     *
     * @param pjp
     * @param o
     * @param environment
     * @return
     */
    public static Object controllerAspect(ProceedingJoinPoint pjp, ObjectMapper o, Environment environment) throws Throwable {
        HttpServletRequest request = getRequestByPjp();
        //关联log和数据库中的日志
        String url = request.getRequestURI();
        String queryString = request.getQueryString();

        List<Object> params = new ArrayList<>();
        Method method = getPjpMethod(pjp);

        // 把所有不含Ignore的参数汇在一起
        for (int i = 0; i < method.getParameterAnnotations().length; i++) {
            boolean b = false;
            for (Annotation ann : method.getParameterAnnotations()[i]) {
                if (ann instanceof ControllerAspectIgnore) {
                    b = true;
                    break;
                }
            }
            if (!b) {
                params.add(pjp.getArgs()[i]);
            }
        }

        ControllerLog clog = getControllerLog(environment, url, getIp(), o, queryString, params);

        Object result;
        result = pjp.proceed();
        if (AnnotationUtils.getAnnotation(method, ControllerAspectIgnore.class) == null) {
            BaseRes b = (BaseRes) result;
            b.setResCode(200);
            b.setResMsg("操作成功！");
            clog.setResult(o.writeValueAsString(result));
        }
        long l = (long) request.getAttribute("yl_starTime");
        clog.setTime(System.currentTimeMillis() - l);
        log.debug("lily-log-stack:{}", o.writeValueAsString(clog));
        return result;
    }

    public static ControllerLog getControllerLog(Environment environment, String url, String ip, ObjectMapper o, String queryString, List<Object> params) throws JsonProcessingException {
        ControllerLog clog = new ControllerLog();

        clog.setGroupId(environment.getProperty("project.groupId"));
        clog.setArtifactId(environment.getProperty("project.artifactId"));
        clog.setVersion(environment.getProperty("project.version"));
        clog.setAuthor(environment.getProperty("project.author"));

        clog.setLogId(UUID.randomUUID().toString());

        clog.setIp(ip);
        clog.setPort(Integer.parseInt(Objects.requireNonNull(environment.getProperty("local.server.port"))));

        clog.setUrl(url);
        clog.setArgs(o.writeValueAsString(params));
        clog.setQueryString(queryString);
        return clog;
    }

    /**
     * MQ 切片记录接收到的原始数据
     */
    public static void rocketMQAspect() {
        // TODO 已写到MQ服务中，回头再提
    }

    /**
     * 通过PJP，获取Request
     *
     * @return
     */
    private static HttpServletRequest getRequestByPjp() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        return sra.getRequest();
    }

    /**
     * 获取反映的方法
     *
     * @param pjp
     * @return
     * @throws NoSuchMethodException
     */
    private static Method getPjpMethod(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Class<?> clazz = methodSignature.getDeclaringType();
        return clazz.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }

    /**
     * 建议项目启动的时候初始化IP，懒得改了
     *
     * @return
     */
    private static String getIp() {
        InetAddress localHost = null;
        try {
            localHost = Inet4Address.getLocalHost();
        } catch (UnknownHostException e) {
            log.error(e.getMessage(), e);
        }
        return localHost.getHostAddress();
    }
}
